package scaladuct

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Sep 1, 2010
 * Time: 10:07:26 PM
 */

object Extensible {
  def extension[T](obj: Any, extClass: Class[T]): Option[T] = {
    if (obj.isInstanceOf[Extensible])
      obj.asInstanceOf[Extensible].extension(extClass)
    else if (extClass.isInstance(obj))
      Some(this.asInstanceOf[T])
    else None
  }
}
trait Extensible {
  def extension[T](extClass: Class[T]): Option[T] = {
    if (extClass.isInstance(this))
      Some(this.asInstanceOf[T])
    else
      None
  }
}

object DummyExtensible extends Extensible

trait ExtensibleDecorator extends Extensible {
  
  def decoratedForExtensible: AnyRef

  override def extension[T](extClass: Class[T]) = {
    val decor = if (decoratedForExtensible == null)
      DummyExtensible
    else
      decoratedForExtensible

    super.extension(extClass) match {
      case None => {
        val dec: AnyRef = decor
        if (dec.isInstanceOf[Extensible])
          dec.asInstanceOf[Extensible].extension(extClass)
        else if (extClass.isInstance(dec)) {
          Some(dec.asInstanceOf[T])
        } else None

      }
      case Some(ext) => Some(ext)
    }
  }
}

